// Fill out your copyright notice in the Description page of Project Settings.

#include "Isalong2.h"
#include "DustWall.h"




ADustWall::ADustWall()
{
	_dMesh->SetDestructibleMesh(ResourceManager::GetResourceManager()->_dustWallMesh);//Done
	_dMesh->SetRelativeLocation(FVector(0, 0, -50));//Done

	_characterBlocker->SetBoxExtent(FVector(5, 50, 50));//Done

	_rayTraceBox->SetBoxExtent(FVector(5, 50,50));//Done
	_overlapBox->SetBoxExtent(FVector(10, 55, 55));//Done

	_distanceView = 200;//Done
	_placingTimespan = 1.0f;//Done

	_itemType = ITEMTYPE_dustWall;//Done
}

void ADustWall::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	if (!_isPlaced)
	{
		if (ToolEdgeSnap())
		{
			_canPlace = GetAroundSupportValue() > 0;
			return;
		}
		if (ToolGetPositionIndex() != -1)
		{
			auto index = ToolGetPositionIndex();
			switch (index)
			{
			case 4:
				ToolUpSnap();
				_canPlace = GetAroundSupportValue() > 0;
				return;
			case 1:case 0:case 2:case 3:
				ToolSideSnap(index);
				_canPlace = GetAroundSupportValue() > 0;
				return;
			}
		}
		if (ToolFootSnap())
		{
			_canPlace = GetAroundSupportValue() > 0;
			return;
		}
		if (ToolLandSnap())
		{
			_canPlace = true;
			return;
		}
		_canPlace = false;
		ToolGoBack();
	}
	else
	{
		if (ToolTickApproach())
		{
			_characterBlocker->SetCollisionEnabled(ECollisionEnabled::NoCollision); //Done
			_dMesh->ApplyRadiusDamage(0.7, GetActorLocation(), 5, 50, false); // Done
			_dMesh->SetSimulatePhysics(true); //Done
		}
	}
}

void ADustWall::BeginPlay()
{
	//set up data
	_sourceMat = _dMesh->GetMaterial(0); //Done
	_dMesh->SetMaterial(0, ResourceManager::_resourceManager->_buildingMat); //Done
	_dynamicMat = _dMesh->CreateDynamicMaterialInstance(0); //Done
}

void ADustWall::OnHurt(AActor* shotter, FVector impactNormal, FVector hitLocation, int HurtType,float hurtValue, UPrimitiveComponent* hitComponent)
{
	switch (HurtType)
	{
	case 11:
		_dMesh->ApplyRadiusDamage(1.2, hitLocation, 15, 4000, false);
		_buildingLife -= 0.5*hurtValue;
		break;
	default:
		_dMesh->ApplyRadiusDamage(0.7, hitLocation, 5, 500, false);
		_buildingLife -= 0.2;
		break;
	}
	// test code
	
	AUIManager::_UIManager->AddDisplayBlood(this,true,3,_buildingLife);


	if (_buildingLife<=0)
	{
		// simulate Physics
		_dMesh->SetSimulatePhysics(true);//Done
		// and close collision
		_characterBlocker->SetCollisionEnabled(ECollisionEnabled::NoCollision);//Done
		ACGameManager::_gameManager->WriteScreen(0, TEXT("Call Kill Actor"));
		ToolKillSelf();
	}
}

// this function called by father
void ADustWall::OnCollisionEnable()
{
	_characterBlocker->SetCollisionEnabled(ECollisionEnabled::QueryOnly);//Done
}

void ADustWall::OnPlaced()
{
	_dMesh->SetMaterial(0, _sourceMat);//Done
}
